package com.jy.wms.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.joyi.gate.comm.SessionInfo;
import com.joyi.gate.safety.vo.UserInfo;
import com.jy.wms.common.UUIDUtils;
import com.jy.wms.common.annotions.BaseServiceDescribe;
import com.jy.wms.common.base.*;
import com.jy.wms.dao.WmsCustomerFileMapper;
import com.jy.wms.dao.WmsOrderChannelMapper;
import com.jy.wms.dao.WmsShipmentOrderDetailedMapper;
import com.jy.wms.dao.WmsShipmentOrderMapper;
import com.jy.wms.pojo.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName: WmsShipmentOrderService.java
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @Author LH
 * @Date Wed Oct 18 11:12:06 GMT+08:00 2017
 */

@Service
public class WmsShipmentOrderService extends BaseService<WmsShipmentOrderMapper, WmsShipmentOrder> {
    private static Logger log = LoggerFactory.getLogger(WmsShipmentOrder.class);
    @Autowired
    private WmsShipmentOrderDetailedMapper wmsShipmentOrderDetailedMapper;

    @Autowired
    private WmsSplitService wmsSplitService;
    @Autowired
    private WmsCustomerFileMapper wmsCustomerFileMapper;
    @Autowired
    WmsShipmentOrderDetailedService wmsShipmentOrderDetailedService;
    @Autowired
    WmsOrderChannelMapper wmsOrderChannelMapper;
    @Autowired
    WmsOrderChannelService wmsOrderChannelService;
    /**
     * 插入一条记录
     *
     * @param map
     * @return int
     */
    public Integer baseInsert(Map<String, Object> map) {
        return dao.baseInsert(map);
    }

    /**
     * 插入一条记录（匹配有值的字段）
     *
     * @param entity 发运订单实体对象
     * @return int
     */
    @Transactional
    @BaseServiceDescribe(moduleName = "发运订单", btnName = "增加订单")
    public Integer baseInsertSelective(WmsShipmentOrder entity) throws Exception {
        //设置日期格式
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // new Date()为获取当前系统时间
        String date = df.format(new Date());
        entity.setCjsj(date);
        entity.setXgsj(date);
        if (CommonInfo.zdsh.getType().equals(entity.getZdsh())) {
            entity.setShr("超级管理员");
            entity.setShzt("1");
        }
        entity.setJhfhsj(df.format(new Date(Long.valueOf(entity.getJhfhsj()).longValue())));
        entity.setYqjhsj(df.format(new Date(Long.valueOf(entity.getYqjhsj()).longValue())));
        //明细集合
        List<WmsShipmentOrderDetailed> lists = entity.getWsodList();
        for (int i = 0; i < lists.size() - 1; i++) {
            for (int j = i + 1; j < lists.size(); j++) {
                if (lists.get(j).getHpid().equals(lists.get(i).getHpid())) {
                    throw new ServiceException("订单明细包含重复货品,添加失败");
                }
            }
        }
        //查询订单编号是否重复(同意货主不可重复)
        Integer e = dao.getCountByBh(entity.getSshzid(), entity.getFybh(), entity.getCkid());
        //判断订单编号是否重复
        if (e <= 0) {
            //保存发运订单
            Integer a = dao.baseInsertSelective(entity);
            Integer b = 0;
            if (a > 0) {
                for (WmsShipmentOrderDetailed wsod : lists) {
                    if (wsod.getScrq() != null && !wsod.getScrq().equals("")) {
                        wsod.setScrq(df.format(new Date(Long.valueOf(wsod.getScrq()).longValue())));
                    }
                    wsod.setSsfyddid(entity.getId());
                    wsod.setCkid(entity.getCkid());
                    wsod.setId(UUIDUtils.uuid());
                    wsod.setCjsj(date);
                    wsod.setLsje(String.valueOf(wsod.getJe()));
                    wmsShipmentOrderDetailedService.insert(wsod);
                    b++;
                }
                //增加订单明细
               // b = wmsShipmentOrderDetailedMapper.baseInsert(lists);
                //当单独为自动审核时,创建完成订单系统直接进行订单拆单。
                if (CommonInfo.zdsh.getType().equals(entity.getZdsh())) {
                    SetAndModifyModel setAndModifyModel = new SetAndModifyModel();
                    List<String> ids = new ArrayList<String>();
                    ids.add(entity.getId());
                    setAndModifyModel.setIds(ids);
                    wmsSplitService.split(setAndModifyModel, entity.getCjr(), entity.getCkid());
                }


                if (b > 0) {
                    throw new SucessException("发运订单添加成功");
                } else {
                    //如果明细添加失败那么回去删掉发运订单
                    Integer c = dao.deleteById(entity.getId());
                    throw new ServiceException("发运订单添加失败");
                }
            } else {
                throw new ServiceException("发运订单添加失败");
            }
        } else {
            throw new ServiceException("发运订单编号重复,添加失败");
        }
    }

    /**
     * 删除（根据主键ID删除）
     *
     * @param id 主键
     * @return int
     */
    public Integer baseDeleteByPrimaryKey(String id) {
        return dao.baseDeleteByPrimaryKey(id);
    }

    /**
     * 删除（根据ID 批量删除）
     *
     * @param id 主键ID列表
     * @return int
     */
    public Integer baseDeleteBathPrimaryKeys(String id) {
        return dao.deleteById(id);
        //return dao.baseDeleteBathPrimaryKeys(idList);
    }

    /**
     * 分页查询
     *
     * @param entity 实体
     * @return Page<WmsShipmentOrder>
     */
    public Page<WmsShipmentOrder> listByBcAndWjh(WmsShipmentOrder entity, String ckid, String hzid) {
        //设置日期格式
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        PageHelper.startPage(entity.getPage(), entity.getRows());
        return (Page<WmsShipmentOrder>) dao.listByBcAndWjh(entity, ckid, hzid);
    }

    /**
     * 分页查询
     *
     * @param entity 实体
     * @return Page<WmsShipmentOrder>
     */
    public Page<WmsShipmentOrder> baseSelectPage(WmsShipmentOrder entity, String ckid, String hzid) {
        //设置日期格式
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        /* if (entity.getCjsj_start() != null && entity.getCjsj_start() != "") {
            entity.setCjsj_start(df.format(new Date(Long.valueOf(entity.getCjsj_start()).longValue())));
        }
        if (entity.getCjsj_end() != null && entity.getCjsj_end() != "") {
            entity.setCjsj_end(df.format(new Date(Long.valueOf(entity.getCjsj_end()).longValue())));
        }
        if (entity.getKhcjsj_start() != null && entity.getKhcjsj_start() != "") {
            entity.setKhcjsj_start(df.format(new Date(Long.valueOf(entity.getKhcjsj_start()).longValue())));
        }
        if (entity.getKhcjsj_end() != null && entity.getKhcjsj_end() != "") {
            entity.setKhcjsj_end(df.format(new Date(Long.valueOf(entity.getKhcjsj_end()).longValue())));
        }
       if (entity.getJhfhsj_start() != null && entity.getJhfhsj_start() != "") {
            entity.setJhfhsj_start(df.format(new Date(Long.valueOf(entity.getJhfhsj_start()).longValue())));
        }
        if (entity.getJhfhsj_end() != null && entity.getJhfhsj_end() != "") {
            entity.setJhfhsj_end(df.format(new Date(Long.valueOf(entity.getJhfhsj_end()).longValue())));
        }
        if (entity.getYqjhsj_start() != null && entity.getYqjhsj_start() != "") {
            entity.setYqjhsj_start(df.format(new Date(Long.valueOf(entity.getYqjhsj_start()).longValue())));
        }
        if (entity.getYqjhsj_end() != null && entity.getYqjhsj_end() != "") {
            entity.setYqjhsj_end(df.format(new Date(Long.valueOf(entity.getYqjhsj_end()).longValue())));
        }*/
        PageHelper.startPage(entity.getPage(), entity.getRows());
        return (Page<WmsShipmentOrder>) dao.baseSelectPage(entity, ckid, hzid);
    }

    /**
     * 查询（根据ID 批量查询）
     *
     * @param idList 主键ID列表
     * @return list
     */
    public Integer baseSelectBathPrimaryKeys(List<WmsShipmentOrder> idList) {
        return dao.baseSelectBathPrimaryKeys(idList);
    }

    /**
     * 修改 （匹配有值的字段）
     *
     * @param entity 主键ID列表
     * @return int
     */
    @BaseServiceDescribe(moduleName = "发运订单", btnName = "修改订单")
    public Integer baseUpdateByPrimaryKeySelective(WmsShipmentOrder entity) throws SucessException, ServiceException {
        //设置日期格式
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date dd = new Date();
        // new Date()为获取当前系统时间
        String date = df.format(dd);

        if (entity.getJhfhsj() != null && entity.getJhfhsj() != "") {
            entity.setJhfhsj(df.format(new Date(Long.valueOf(entity.getJhfhsj()).longValue())));
        }
        if (entity.getYqjhsj() != null && entity.getYqjhsj() != "") {
            entity.setYqjhsj(df.format(new Date(Long.valueOf(entity.getYqjhsj()).longValue())));
        }
        WmsShipmentOrder wmsShipmentOrder = dao.baseSelectByPrimaryKey(entity.getId());//通过id查询对象
        if (wmsShipmentOrder.getCdzt().equals(CommonInfo.shipmentOrder_ycd.getType())) {
            throw new ServiceException("订单已拆单，不可以编辑");
        } else {
            Integer e = 0;
            if (wmsShipmentOrder.getFybh().equals(entity.getFybh())) {
                entity.setFybh("");
            } else {
                //查询订单编号是否重复(同一货主不可重复)
                e = dao.getCountByBh(entity.getSshzid(), entity.getFybh(), entity.getCkid());
            }
            if (e <= 0) {
                //修改发运订单
                Integer a = dao.baseUpdateByPrimaryKeySelective(entity);
                if (a > 0) {
                    throw new SucessException("发运订单修改成功");
                } else {
                    throw new ServiceException("发运订单修改失败");
                }
            } else {
                throw new ServiceException("订单编号重复，修改失败");
            }
        }
    }

    /**
     * 修改（根据主键ID修改）
     *
     * @param entity 主键ID列表
     * @return int
     */
    public Integer baseUpdateByPrimaryKey(WmsShipmentOrder entity) {
        return dao.baseUpdateByPrimaryKey(entity);
    }

    /**
     * 获取客户信息
     *
     * @param hzid
     * @param ckid
     * @return
     * @throws ServiceException
     */
    @BaseServiceDescribe(moduleName = "发运订单", btnName = "获取客户信息")
    public List<WmsCustomerFile> getCusInfo(String hzid, String ckid, String khbh) throws ServiceException {
        try {
            return dao.getCusInfo(hzid, ckid, khbh);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("获取客户信息", e);
        }

    }

    /**
     * 获取货主下的货品
     *
     * @param hzid 货主id
     * @return
     */
    @BaseServiceDescribe(moduleName = "发运订单", btnName = "获取货主下的货品")
    public List<WmsGoods> getGoodsByHzid(String hzid, String ckid, String bh) throws ServiceException {
        try {
            return dao.getGoodsByHzid(hzid, ckid, bh);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("获取货品", e);
        }
    }

    /**
     * 获取货主下的库位
     *
     * @param hzid
     * @param ckid
     * @return
     */
    @BaseServiceDescribe(moduleName = "发运订单", btnName = "获取库位")
    public List<WmsLibraryPosition> getLiLibraryPosition(String hzid, String ckid, String mc) throws ServiceException {
        try {
            return dao.getLiLibraryPosition(hzid, ckid, mc);
        } catch (Exception e) {

            throw new ServiceException("获取库位", e);
        }

    }

    /**
     * 获取库存
     *
     * @param ckid
     * @return
     */
    @BaseServiceDescribe(moduleName = "发运订单", btnName = "获取库存")
    public List<WmsStock> getWmsStock(String hpid, String ckid, String hppc) throws ServiceException {
        try {
            return dao.getWmsStock(hpid, ckid, hppc);
        } catch (Exception e) {

            throw new ServiceException("获取库存", e);
        }
    }

    @BaseServiceDescribe(moduleName = "发运订单", btnName = "获取库存")
    public List<WmsStock> getWmsStockScrq(String hpid, String ckid, String scrq) throws ServiceException {
        try {
            return dao.getWmsStockScrq(hpid, ckid, scrq);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("获取库存", e);
        }
    }


    /**
     * 作废时修改是否有效的状态
     *
     * @param idList 运单id
     * @param zfr    作废人
     * @return
     */
    @BaseServiceDescribe(moduleName = "发运订单", btnName = "作废发运订单")
    public Integer updateSfyx(List<String> idList, String zfr) throws SucessException, ServiceException {
        List<WmsShipmentOrder> list = dao.getOrderList(idList);
        List<String> list2 = new ArrayList<String>();
        for (WmsShipmentOrder wpo : list) {
            //未拆单（只能作废拆单状态为“未拆单”下的发运订单 ，将未拆单的发运订单标记为无效。）
            if (CommonInfo.shipmentOrder_wcd.getType().equals(wpo.getCdzt())) {
                list2.add(wpo.getId());
                //只能作废一次（作废是否有效状态为 有效 的记录）
                /*if (CommonInfo.shipmentOrder_sfyx_yx.getType().equals(wpo.getSfyx())) {
                    list2.add(wpo.getId());
                }*/
            }
        }

        if (list2.size() > 0) {
            //删除发运订单
            Integer a =  dao.baseDeleteBathPrimaryKeys(list2);
            //删除明细
            Integer b =  dao.deleteMx(list2);
            if (a > 0) {
                throw new SucessException("选中" + idList.size() + "条记录，删除成功" + a + "条记录");
            } else {
                throw new ServiceException("发运订单删除失败");
            }
        }  else {
            throw new ServiceException("只能删除未拆单的记录");
        }
        /*if (list2.size() > 0) {
            //修改发运订单
            Integer a = dao.updateSfyx(list2, zfr);
            if (a > 0) {
                throw new SucessException("选中" + idList.size() + "条记录，作废成功" + a + "条记录");
            } else {
                throw new ServiceException("发运订单作废失败");
            }
        } else {
            throw new ServiceException("选中的记录已审核或已作废，不可以进行此操作");
        }*/
    }


    /**
     * 标记发运完成
     *
     * @param bjr  标记人
     * @param bjyy 标记原因
     * @return
     */
    @BaseServiceDescribe(moduleName = "发运订单", btnName = "标记发运订单")
    @Transactional
    public Integer updateZt(List<String> idList, String bjr, String bjyy) throws SucessException, ServiceException {
        List<WmsShipmentOrder> list = dao.getOrderList(idList);
        List<String> list2 = new ArrayList<String>();
        for (WmsShipmentOrder wpo : list) {
            //部分发运（	只能操作部分发运下的发运订单）
            if ("3".equals(wpo.getFyzt())) {
                list2.add(wpo.getId());
            }
        }
        if (list2.size() > 0) {
            //修改发运订单
            Integer a = dao.updateZt(list2, bjr, bjyy);
            Integer b = dao.updateMxZt(list2);//修改明细
            if (a > 0) {
                throw new SucessException("选中" + idList.size() + "条记录，标记成功" + a + "条记录");
            } else {
                throw new ServiceException("发运订单标记失败");
            }
        } else {
            throw new ServiceException("选中的记录不包含部分发运状态的订单，不可以标记");
        }
    }


    /**
     * 审核发运订单
     *
     * @param setAndModifyModel 发运订单ids
     * @return
     */
    @BaseServiceDescribe(moduleName = "发运订单", btnName = "审核发运订单")
    @Transactional
    public Integer updateShzt(SetAndModifyModel setAndModifyModel, String shr, String ckid) throws Exception {
        List<WmsShipmentOrder> list = dao.getOrderList(setAndModifyModel.getIds());
        List<String> list2 = new ArrayList<String>();
        for (WmsShipmentOrder wpo : list) {
            //未审核
            if (CommonInfo.shipmentOrder_wsh.getType().equals(wpo.getShzt())) {
                list2.add(wpo.getId());
            }
        }
        if (list2.size() > 0) {
            Integer a = dao.updateShzt(list2, shr);
            //单据审核完毕后,系统直接进行订单拆单；
            wmsSplitService.split(setAndModifyModel, shr, ckid);


            if (a > 0) {
                throw new SucessException("选中" + setAndModifyModel.getIds().size() + "条记录，审核成功" + a + "条记录");
            } else {
                throw new ServiceException("发运订单审核失败");
            }
        } else {
            throw new ServiceException("选中的记录已经全部审核，不可以再次审核");
        }

    }


    /**
     * 查看获取发运订单
     *
     * @param
     * @return
     */
    /*@BaseServiceDescribe(moduleName = "发运订单", btnName = "查看发运订单")
    public WmsShipmentOrder getWmsShipmentOrder() throws SucessException, ServiceException {
       WmsShipmentOrder wmsShipmentOrder= dao.getWmsShipmentOrder();
       if(wmsShipmentOrder!=null){
           throw new SucessException("发运订单审核");
       } else {
              throw new ServiceException("发运订单审核");
       }
    }*/
    @BaseServiceDescribe(moduleName = "发运订单", btnName = "查询发运订单及明细")
    public JSONObject baseSelectByPrimaryKey(String id, String hzid, String ckid) throws ServiceException {
        try {
            JSONObject jb = new JSONObject();
            //发运订单
            WmsShipmentOrder wpo = dao.baseSelectByPrimaryKey(id);
            JSONObject wmsShipmentOrder = JSONObject.fromObject(wpo);
            //发运订单明细
            List<WmsShipmentOrderDetailed> list = dao.wmsShipmentOrderDetailedList(id, hzid, ckid);
            JSONArray wmsShipmentOrderDetailed = JSONArray.fromObject(list);
            jb.put("wmsShipmentOrder", wmsShipmentOrder);
            jb.put("wmsShipmentOrderDetailed", wmsShipmentOrderDetailed);
            return jb;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("查询发运订单及明细", e);
        }
    }

    @BaseServiceDescribe(moduleName = "发运订单", btnName = "查询明细集合")
    public JSONArray getDetailList(String id, String hzid, String ckid) throws ServiceException {
        try {

            //发运订单明细
            List<WmsShipmentOrderDetailed> list = dao.wmsShipmentOrderDetailedList(id, hzid, ckid);
            return JSONArray.fromObject(list);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("查询发运订单及明细", e);
        }
    }

    @BaseServiceDescribe(moduleName = "发运订单", btnName = "导入发运订单")
    public void importExcle(HttpSession session, String filepath, String type) throws ServiceException, SucessException, Exception {
        ImportParams params = new ImportParams();
        params.setNeedSave(false);
        params.setTitleRows(0);
        params.setHeadRows(1);
        if(type.equals("ZX")){
            params.setDataHanlder(new ShipmentOrderMapImportHanlder());
        }else{
            params.setDataHanlder(new ShipmentOrderMapOAImportHanlder());
        }

        UserInfo userinfo = (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
        List<SysHz> hz = (List<SysHz>) session.getAttribute(BaseSessionInfo.SessionConsignor);
        //仓库编号
        String ckid = String.valueOf(userinfo.getUser().getOrgId().get(0));
                //货主id
        String hzid = null;
        if (hz.size() > 0) {
            hzid = hz.get(0).getHzid();
        }

        //设置日期格式
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d = new Date();
        String date = df.format(d);
        Calendar cl = Calendar.getInstance();
        cl.setTime(d);
        cl.add(Calendar.DATE, 3);
        //预期交货时间
        String yqjhsj = df.format(cl.getTime());
        //JSONObject jb = JSONObject.fromObject(filepath);
        //URL url = new URL((String) jb.get("filepath"));
       // URL url = new URL(filepath);
       // URLConnection conn = url.openConnection();
     /*   List<Map<String, Object>> result = ExcelImportUtil.importExcel(
                conn.getInputStream(),
                Map.class, params);*/
        List<Map<String, Object>> result = ExcelImportUtil.importExcel(
                new File(filepath),
                Map.class, params);
//        List<Map<String, Object>> result = ExcelImportUtil.importExcel(
//                new File(PoiPublicUtil.getWebRootPath("import/111发货通知单（新）发运部_1(1).xlsx")),
//                Map.class, params);
        System.out.println("result:"+result);
        log.info("result:"+result);

        /*File tempFile =null;
        if(!multipartFile.isEmpty()) {
            String filePath = session.getServletContext().getRealPath("/") + "upload/";
            File dir = new File(filePath);
            if (!dir.exists()) {
                dir.mkdir();
            }
            String path = filePath + multipartFile.getOriginalFilename();
             tempFile = tempFile = new File(path);
            multipartFile.transferTo(tempFile);
        }
         List<Map<String, Object>> result = ExcelImportUtil.importExcel(
                 tempFile,
                Map.class, params);
                */
        for (int i = 0; i < result.size(); i++) {
            result.get(i).put("num", i + 2);
        }
        //表格去重
      //  removeDuplicate(result);
        //数据库去重
        removeDataDuplicate(result, hzid, ckid);
        //判断表格中是否有错误数据
        removeError(result, session,type);
        Map<String, Map> map = new HashMap<String, Map>();
        List list = new ArrayList();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < result.size(); i++) {
            //判断读取的时间格式是数字还是文本，如果是数字就转成文本格式的时间
            Boolean aBoolean=false;
            Boolean bBoolean=false;
            if(result.get(i).get("khcjsj")!=null){
                 aBoolean=StringUtils.isNumeric(result.get(i).get("khcjsj").toString());
            }
            if(result.get(i).get("yjrq")!=null){
                 bBoolean=StringUtils.isNumeric(result.get(i).get("yjrq").toString());

            }

            if( result.get(i).get("khcjsj")!=null &&result.get(i).get("khcjsj")!=""&& !result.get(i).get("khcjsj").equals("") && result.get(i).get("khcjsj").toString().contains("年")){
                String cjsj= result.get(i).get("khcjsj").toString().replace("年","-").replace("月","-").replace("日","");
                System.out.println(  result.get(i).get("khcjsj").toString());
                result.get(i).put("khcjsj",cjsj);
            }else if(result.get(i).get("khcjsj")!=null &&result.get(i).get("khcjsj")!=""&& !result.get(i).get("khcjsj").equals("") && aBoolean==true){
                result.get(i).put("khcjsj", sdf.format(HSSFDateUtil.getJavaDate(Integer.valueOf(result.get(i).get("khcjsj").toString()))));
            }
            if(result.get(i).get("yjrq")!=null &&result.get(i).get("yjrq")!=""&& !result.get(i).get("yjrq").equals("") && bBoolean==true){
                result.get(i).put("yjrq", sdf.format(HSSFDateUtil.getJavaDate(Integer.valueOf(result.get(i).get("yjrq").toString()))));
            }
            WmsOrderChannel wmsOrderChannel=null;
            //订单渠道
            if(type.equals("ZX")){
                 wmsOrderChannel= dao.getOrderChannel(hzid,ckid,(String) result.get(i).get("qdbh"));
            }else{
                wmsOrderChannel=new WmsOrderChannel();
                //OA导入新增订单渠道
               String id= channelInster(hzid,ckid,(String) result.get(i).get("yiji"),(String) result.get(i).get("erji"));
               wmsOrderChannel.setId(id);
            }
            if(result.get(i).get("hybh")==null){
                result.get(i).put("hybh","");
            }
             //根据名称，货主查找客户对象
              WmsCustomerFile wmsCustomerFile = dao.getCustomerFile((String) result.get(i).get("lxrxm").toString(), result.get(i).get("lxrdh").toString(),hzid, ckid);

            // 根据地址（省，市）查询线路
            List<WmsLineDetailed> wmsLineDetailed = dao.getWmsLineDetailed(result.get(i).get("sheng").toString(), result.get(i).get("shi").toString());
            WmsCustomerFile wmsCustomerFile1=new WmsCustomerFile();
           //如果存在当前客户档案，则修改客户档案，如果没有就新增客户档案
            if(wmsCustomerFile==null){//新增客户档案
                wmsCustomerFile= saveCustomFile(ckid, hzid, result, i, wmsCustomerFile, wmsLineDetailed,wmsCustomerFile1);
            }else{//修改客户档案
                updateCustomFile(ckid, hzid, result, i, wmsCustomerFile, wmsLineDetailed,wmsCustomerFile1);
            }
            //类型对象
            WmsOwnerOrdertype wmsOwnerOrdertype = dao.getWmsOwnerOrderType((String) result.get(i).get("fylx").toString(), hzid, ckid);
            //货品对象
            WmsGoods wmsGoods = dao.getGoods((String) result.get(i).get("hpbh"), ckid);
            result.get(i).put("id", UUIDUtils.uuid());
            result.get(i).put("sshzid", hzid);
            result.get(i).put("khid", wmsCustomerFile.getId());
            result.get(i).put("dz", result.get(i).get("sheng").toString()+result.get(i).get("shi").toString()+result.get(i).get("xq").toString()+result.get(i).get("khdz").toString());
            result.get(i).put("lxid", wmsOwnerOrdertype.getId());
            result.get(i).put("khddh", result.get(i).get("fybh"));
            result.get(i).put("cjsj", date);
            result.get(i).put("cjr", userinfo.getUser().getName());
            result.get(i).put("ckid", ckid);
          //  if(type.equals("ZX")){
                result.get(i).put("ddqdid", wmsOrderChannel.getId());
          //  }

            if(result.get(i).get("jhfs")==null||result.get(i).get("jhfs").equals("")||result.get(i).get("jhfs").equals("发运")){
                result.get(i).put("jhfs",0);
            }else if(result.get(i).get("jhfs").equals("自提")){
                result.get(i).put("jhfs",1);
            }else if(result.get(i).get("jhfs").equals("到付")){
                result.get(i).put("jhfs",2);
            }else{//如果填写的不是以上三种，那么默认为“发运”
                result.get(i).put("jhfs",0);
            }
           // 查看是否有抵扣行这个列，如果有的话要一起去匹配抵扣数量这个字段，把明细数量作为抵扣数量
            if(result.get(i).get("bs")==null){
                result.get(i).put("bs","0");
            }else{
                result.get(i).put("dksl",result.get(i).get("yqsl"));
                if(result.get(i).get("bs").equals("发运行")){
                    result.get(i).put("bs","0");
                }else if(result.get(i).get("bs").equals("抵扣行")){
                    result.get(i).put("bs","1");
                }
            }
            result.get(i).put("fylx", wmsOwnerOrdertype.getId());
            //result.get(i).put("yqjhsj", yqjhsj); //要求交货时间
            result.get(i).put("hpid", wmsGoods.getId()); //货品id
            result.get(i).put("zdw", wmsGoods.getZdw());//主单位
            result.get(i).put("lsje", Double.parseDouble(wmsGoods.getJe())* Double.parseDouble(result.get(i).get("yqsl").toString()));
            if (result.get(i).get("yqsl") != null && result.get(i).get("yqsl") != "" && wmsGoods.getZdwsl() != null && wmsGoods.getZdwsl() != "") {
                Integer num1 = Integer.parseInt((String) result.get(i).get("yqsl")) / Integer.parseInt(wmsGoods.getZdwsl());
                Integer num2 = Integer.parseInt((String) result.get(i).get("yqsl")) % Integer.parseInt(wmsGoods.getZdwsl());
                result.get(i).put("yqxdwsl", num1 + "箱" + num2 + "件"); //货品数量（箱单位数量）
            }
            result.get(i).put("mxid", UUIDUtils.uuid());
            //自动审核时默认已审核
           /* if (CommonInfo.zdsh.getType().equals(wmsOwnerOrdertype.getZdsh())) {
                result.get(i).put("shzt", "1");
                result.get(i).put("shr", "超级管理员");
            } else {
                //否则默认为未审核
                result.get(i).put("shzt", "0");
                result.get(i).put("shr", "");
            }*/
           // 表格中可能存在一个订单下有多条明细的情况，此时做一个判断；如果数据中已经存在该发运编号，那么，只增加发运明细，否则，主表和明细表一块增加记录
           // Integer num = dao.getCountByBh(hzid, (String) result.get(i).get("fybh"), ckid);//发运编号的数量
            List<WmsShipmentOrder> lists= dao.selectList(new EntityWrapper<WmsShipmentOrder>().eq("sshzid",hzid).eq("fybh", (String) result.get(i).get("fybh")).eq("ckid",ckid));

            if(lists.size()>0){
                result.get(i).put("ssfyddid", lists.get(0).getId());
                //保存订单明细
                //查询当前订单下的当前货品是否已经存在，导入用
                //如果是发运行，那么相同订单下的相同货品进行合并，数量累加
                WmsShipmentOrderDetailed wmsShipmentOrderDetailed=null;
                if(((String)result.get(i).get("bs")).equals("0")){
                     wmsShipmentOrderDetailed= dao.getHpDetailCount(lists.get(0).getId(),(String)result.get(i).get("hpbh"),(String)result.get(i).get("bs"));
                }
               //如果发运明细不为空，修改查到的明细的预期数量，否则新增一条明细
               if(wmsShipmentOrderDetailed!=null){
                   updateMx(result, i, wmsGoods, wmsShipmentOrderDetailed);
               }else {
                   Integer b = wmsShipmentOrderDetailedMapper.baseInsertByMap(result.get(i));
               }

                //查看该货品是否有配件，如果有配件的话查询配件的信息一块放入明细表
                saveGoodAccessories(result, i, wmsGoods,ckid);
            }else {
                result.get(i).put("ssfyddid", result.get(i).get("id"));
                //订单保存
                Integer a = dao.baseInsert(result.get(i));

                //查询当前订单下的当前货品是否已经存在，导入用i
                WmsShipmentOrderDetailed wmsShipmentOrderDetailed= dao.getHpDetailCount((String)result.get(i).get("id"),(String)result.get(i).get("hpbh"),(String)result.get(i).get("bs"));
                //如果发运明细不为空，修改查到的明细的预期数量，否则新增一条明细
                if(wmsShipmentOrderDetailed!=null){
                    updateMx(result, i, wmsGoods, wmsShipmentOrderDetailed);
                }else {
                    Integer b = wmsShipmentOrderDetailedMapper.baseInsertByMap(result.get(i));
                }
                //查看该货品是否有配件，如果有配件的话查询配件的信息一块放入明细表
                saveGoodAccessories(result, i, wmsGoods,ckid);
            }

            System.out.println(result.get(i));
        }
        throw new SucessException("发运订单导入成功");
    }

    /**
     * OA导入新增订单渠道
     * @param hzid
     * @param ckid
     * @param yiji
     * @param erji
     * @return
     */
    private String channelInster(String hzid, String ckid, String yiji, String erji){
        WmsOrderChannel wmsOrderChannel= new WmsOrderChannel();
        if(!"".equals(yiji)&& yiji!=null){
            //判断是否存在一级
            List<WmsOrderChannel> wmsOrder = dao.selectOrderChannel(hzid, ckid,yiji,"0");
            if(wmsOrder.size()>0){
                //存在二级,查询所有的二级
                if(!"".equals(erji)&& erji!=null) {
                    List<WmsOrderChannel> channels = dao.selectOrderChannel(hzid, ckid, erji, wmsOrder.get(0).getId());
                    if (channels.size() > 0) {
                        //有二级先匹配是否有二级
                        int status = 0;//记录是否有匹配上的数据
                        //遍历所得的二级此目录下有二级
                        for (WmsOrderChannel order : channels) {
                                if (erji.equals(order.getMc())) {
                                    status = 1;
                                    wmsOrderChannel.setId(order.getId());
                                }
                        }
                        if(status!=1){
                            //新增二级
                            WmsOrderChannel orderChannel2 = new WmsOrderChannel();
                            orderChannel2.setId(UUIDUtils.uuid());
                            orderChannel2.setSshzid(hzid);
                            orderChannel2.setCkid(ckid);
                            orderChannel2.setMc(erji);
                            int count1 = wmsOrderChannelMapper.countSumByFjd(wmsOrder.get(0).getId());
                            orderChannel2.setWz(String.valueOf(count1 + 1));
                            orderChannel2.setCode(wmsOrderChannelService.code());
                            orderChannel2.setSq("1");
                            orderChannel2.setMs(erji);
                            orderChannel2.setFjd(wmsOrder.get(0).getId());
                            int k = wmsOrderChannelMapper.baseInsert(orderChannel2);
                            if (k > 0) {
                                wmsOrderChannel.setId(orderChannel2.getId());
                            } else {
                                throw new RuntimeException("新增订单渠道失败");
                            }
                        }
                    } else {
                        //此目录下无二级，新增二级即可
                        //新增2级
                        WmsOrderChannel orderChannel2 = new WmsOrderChannel();
                        orderChannel2.setId(UUIDUtils.uuid());
                        orderChannel2.setSshzid(hzid);
                        orderChannel2.setCkid(ckid);
                        orderChannel2.setMc(erji);
                        int count1 = wmsOrderChannelMapper.countSumByFjd(wmsOrder.get(0).getId());
                        orderChannel2.setWz(String.valueOf(count1 + 1));
                        orderChannel2.setCode(wmsOrderChannelService.code());
                        orderChannel2.setSq("1");
                        orderChannel2.setMs(erji);
                        orderChannel2.setFjd(wmsOrder.get(0).getId());
                        int k = wmsOrderChannelMapper.baseInsert(orderChannel2);
                        if (k > 0) {
                            wmsOrderChannel.setId(orderChannel2.getId());
                        } else {
                            throw new RuntimeException("新增订单渠道失败");
                        }

                    }
                }else{
                    wmsOrderChannel.setId(wmsOrder.get(0).getId());
                }
            }else{
                //不存在，新增一级二级
                WmsOrderChannel orderChannel1=new WmsOrderChannel();
                orderChannel1.setId(UUIDUtils.uuid());
                orderChannel1.setSshzid(hzid);
                orderChannel1.setCkid(ckid);
                orderChannel1.setMc(yiji);
                int count=wmsOrderChannelMapper.countSumByFjd("0");
                orderChannel1.setWz(String.valueOf(count+1));
                orderChannel1.setCode(wmsOrderChannelService.code());
                orderChannel1.setSq("1");
                orderChannel1.setMs(yiji);
                orderChannel1.setFjd("0");
                int f=wmsOrderChannelMapper.baseInsert(orderChannel1);
                if(f>0){
                    if(!"".equals(erji)&& erji!=null) {
                        //新增2级
                        WmsOrderChannel orderChannel2 = new WmsOrderChannel();
                        orderChannel2.setId(UUIDUtils.uuid());
                        orderChannel2.setSshzid(hzid);
                        orderChannel2.setCkid(ckid);
                        orderChannel2.setMc(erji);
                        int count1 = wmsOrderChannelMapper.countSumByFjd(orderChannel1.getId());
                        orderChannel2.setWz(String.valueOf(count1 + 1));
                        orderChannel2.setCode(wmsOrderChannelService.code());
                        orderChannel2.setSq("1");
                        orderChannel2.setMs(erji);
                        orderChannel2.setFjd(orderChannel1.getId());
                        int k = wmsOrderChannelMapper.baseInsert(orderChannel2);
                        if (k > 0) {
                            wmsOrderChannel.setId(orderChannel2.getId());
                        } else {
                            throw new RuntimeException("新增订单渠道失败");
                        }
                    }else{
                        //如果无二级直接关联一级Id
                        wmsOrderChannel.setId(orderChannel1.getId());
                    }
                }else{
                    throw new RuntimeException("新增订单渠道失败");
                }
            }
        }
        return wmsOrderChannel.getId();
    }
    private void updateMx(List<Map<String, Object>> result, int i, WmsGoods wmsGoods, WmsShipmentOrderDetailed wmsShipmentOrderDetailed) {
        wmsShipmentOrderDetailed.setYqsl(String.valueOf(Integer.parseInt((String)result.get(i).get("yqsl"))+ Integer.parseInt(wmsShipmentOrderDetailed.getYqsl())));
        Integer num1 = Integer.parseInt(wmsShipmentOrderDetailed.getYqsl()) / Integer.parseInt(wmsGoods.getZdwsl());
        Integer num2 = Integer.parseInt(wmsShipmentOrderDetailed.getYqsl()) % Integer.parseInt(wmsGoods.getZdwsl());
        wmsShipmentOrderDetailed.setYqxdwsl(num1 + "箱" + num2 + "件");//货品数量（箱单位数量）
        wmsShipmentOrderDetailedMapper.baseUpdateByPrimaryKeySelective(wmsShipmentOrderDetailed);
    }



    private void updateCustomFile(String ckid, String hzid, List<Map<String, Object>> result, int i, WmsCustomerFile wmsCustomerFile, List<WmsLineDetailed> wmsLineDetailed, WmsCustomerFile wmsCustomerFile1) {
        wmsCustomerFile.setDz(result.get(i).get("khdz").toString());
        wmsCustomerFile.setSheng(result.get(i).get("sheng").toString());
        wmsCustomerFile.setShi(result.get(i).get("shi").toString());
        wmsCustomerFileMapper.baseUpdateByPrimaryKeySelective(wmsCustomerFile);


    }
    //保存客户档案
    private WmsCustomerFile saveCustomFile(String ckid, String hzid, List<Map<String, Object>> result, int i, WmsCustomerFile wmsCustomerFile, List<WmsLineDetailed> wmsLineDetailed, WmsCustomerFile wmsCustomerFile1) {
        //if (wmsCustomerFile == null) {
            wmsCustomerFile=new WmsCustomerFile();
            wmsCustomerFile.setId(UUIDUtils.uuid());
            wmsCustomerFile.setSshzid(hzid);
            wmsCustomerFile.setKhlx("0");//收货人
        if(result.get(i).get("lxrdh")!=null){
            wmsCustomerFile.setKhbh(result.get(i).get("lxrdh").toString());
        }
        if(result.get(i).get("lxrxm")!=null){
            wmsCustomerFile.setKhmc(result.get(i).get("lxrxm").toString());
        }
        if(result.get(i).get("khdz")!=null){
            wmsCustomerFile.setDz(result.get(i).get("khdz").toString());
        }
        if(result.get(i).get("sheng")!=null){
            wmsCustomerFile.setSheng(result.get(i).get("sheng").toString());
        }
        if(result.get(i).get("shi")!=null){
            wmsCustomerFile.setShi(result.get(i).get("shi").toString());
        }
        if(result.get(i).get("lxrdh")!=null){
            wmsCustomerFile.setLxrdh(result.get(i).get("lxrdh").toString());
        }
        if(result.get(i).get("lxrxm")!=null){
            wmsCustomerFile.setLxrxm(result.get(i).get("lxrxm").toString());
        }

        if(result.get(i).get("hyxm")!=null){
            wmsCustomerFile.setHyxm(result.get(i).get("hyxm").toString());
        }
            wmsCustomerFile.setCkid(ckid);
            wmsCustomerFile.setLxid(wmsLineDetailed.get(0).getXlid());
            int a = wmsCustomerFileMapper.baseInsertSelective(wmsCustomerFile);
        //}
        return wmsCustomerFile;
    }

    private void saveGoodAccessories(List<Map<String, Object>> result, int i, WmsGoods wmsGoods, String ckid) {
        if(wmsGoods.getZhhp().equals("1")){
            //货品包含的配件货品
            List<WmsGoods> goodList=dao.getGoodAccessories(wmsGoods.getId(),ckid);
            for(WmsGoods wg:goodList){
                result.get(i).put("hpid", wg.getId()); //货品id
                result.get(i).put("zdw", wg.getZdw());//主单位
               // result.get(i).put("yqsl", result.get(i).get("yqsl")); //货品数量（主单位数量）
                result.get(i).put("lsje", Double.parseDouble(wg.getJe())* Double.parseDouble(result.get(i).get("yqsl").toString()));
                if (result.get(i).get("yqsl") != null && result.get(i).get("yqsl") != "" && wmsGoods.getZdwsl() != null && wmsGoods.getZdwsl() != "") {
                    Integer num1 = Integer.parseInt((String) result.get(i).get("yqsl")) / Integer.parseInt(wmsGoods.getZdwsl());
                    Integer num2 = Integer.parseInt((String) result.get(i).get("yqsl")) % Integer.parseInt(wmsGoods.getZdwsl());
                    result.get(i).put("yqxdwsl", num1 + "箱" + num2 + "件"); //货品数量（箱单位数量）
                }
                result.get(i).put("mxid", UUIDUtils.uuid());
                //查询当前订单下的当前货品是否已经存在，导入用
                WmsShipmentOrderDetailed wmsShipmentOrderDetailed= dao.getHpDetailCount((String)result.get(i).get("ssfyddid"),wg.getBh(),(String)result.get(i).get("bs"));
                //如果发运明细不为空，修改查到的明细的预期数量，否则新增一条明细
                if(wmsShipmentOrderDetailed!=null){
                    wmsShipmentOrderDetailed.setYqsl(String.valueOf(Integer.parseInt((String)result.get(i).get("yqsl"))+ Integer.parseInt(wmsShipmentOrderDetailed.getYqsl())));
                    wmsShipmentOrderDetailedMapper.baseUpdateByPrimaryKeySelective(wmsShipmentOrderDetailed);
                }else {
                    Integer b = wmsShipmentOrderDetailedMapper.baseInsertByMap(result.get(i));
                }

            }

        }
    }



    /**
     * 查找有错的记录
     *
     * @param lis
     */
    public void removeError(List<Map<String, Object>> lis, HttpSession session, String type) throws ServiceException {
        UserInfo userinfo = (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
        List<SysHz> hz = (List<SysHz>) session.getAttribute(BaseSessionInfo.SessionConsignor);
        //仓库编号
       String ckid = String.valueOf(userinfo.getUser().getOrgId().get(0));
        //货主id
        String hzid = null;
        if (hz.size() > 0) {
            hzid = hz.get(0).getHzid();
        }

        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < lis.size(); i++) {
         // 根据地址（省，市）查询线路
            List<WmsLineDetailed> wmsLineDetailed = dao.getWmsLineDetailed(lis.get(i).get("sheng").toString().trim(), lis.get(i).get("shi").toString().trim());
            //类型对象
            WmsOwnerOrdertype wmsOwnerOrdertype = dao.getWmsOwnerOrderType((String) lis.get(i).get("fylx").toString(), hzid, ckid);
            //货品对象
            WmsGoods wmsGoods = dao.getGoods((String) lis.get(i).get("hpbh"), ckid);
            WmsOrderChannel wmsOrderChannel=null;
            //订单渠道
             if(type.equals("ZX")){
                 wmsOrderChannel= dao.getOrderChannel(hzid,ckid,(String) lis.get(i).get("qdbh"));
             }


            if ( wmsOwnerOrdertype == null || wmsGoods == null||wmsLineDetailed==null
                    ||(type.equals("ZX")&&wmsOrderChannel==null)
                    ||(type.equals("OA")&&(lis.get(i).get("yiji")==null||lis.get(i).get("erji")==null||lis.get(i).get("yiji").equals("")||lis.get(i).get("erji").equals("")))
                    ||lis.get(i).get("fybh")==null||lis.get(i).get("fybh").equals("")
                    ||lis.get(i).get("lxrxm")==null||lis.get(i).get("lxrdh")==null||lis.get(i).get("lxrxm").equals("") ||lis.get(i).get("lxrdh").equals("")
                    ) {
                sb.append("第" + lis.get(i).get("num") + "行，订单号为" + lis.get(i).get("fybh") + "的记录");
            }
            if(lis.get(i).get("fybh").equals("")||lis.get(i).get("fybh") ==null){
                sb.append(",订单号不可为空");
            }
            if (wmsOwnerOrdertype == null) {
                sb.append(",单据类型不存在");
            }
            if (wmsGoods == null) {
                sb.append(",货品编号不存在；");
            }
            if(wmsLineDetailed.size()==0){
               sb.append(",路线不存在；");
            }
            if(type.equals("ZX")&&wmsOrderChannel==null){
                sb.append(",订单渠道不存在；");
            }
           if(type.equals("OA")&&(lis.get(i).get("yiji")==null||lis.get(i).get("yiji").equals(""))){
                sb.append(",一级不可为空；");
            }
            if(type.equals("OA")&&(lis.get(i).get("erji")==null||lis.get(i).get("erji").equals(""))){
                sb.append(",二级不可为空；");
            }

           if(lis.get(i).get("lxrxm").equals("")||lis.get(i).get("lxrxm") ==null){
               sb.append("收货人姓名不可为空；");
           }
            if(lis.get(i).get("lxrdh").equals("")||lis.get(i).get("lxrdh") ==null){
                sb.append(",联系电话不可为空；");
            }
        }


        if (sb != null && !"".equals(sb) && sb.length() > 0) {
            throw new ServiceException("表格中" + sb);
        }
    }

    /**
     * 报表内去重
     */
    public void removeDuplicate(List<Map<String, Object>> lis) throws ServiceException {
        //报表内不允许存在相同订单号下有相同货品的情况
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < lis.size() - 1; i++) {
            for (int j = i + 1; j < lis.size(); j++) {
                //JSONObject jb = new JSONObject();
                if (lis.get(j).get("fybh").equals(lis.get(i).get("fybh")) && lis.get(j).get("hpbh").equals(lis.get(i).get("hpbh"))) {
                    sb.append("第" + lis.get(j).get("num") + "行，订单号：" + lis.get(j).get("fybh") + "，货品编号:" + lis.get(j).get("hpbh") + ",");
                    lis.remove(j);
                    j--;
                }
            }
        }
        if (sb != null && !"".equals(sb) && sb.length() > 0) {
            throw new ServiceException("表格中" + sb + "货品重复，导入失败");
        }

    }

    /**
     * 数据库去重
     *
     * @param lis
     * @param hzid
     * @param ckid
     * @throws ServiceException
     */
    public void removeDataDuplicate(List<Map<String, Object>> lis, String hzid, String ckid) throws ServiceException {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < lis.size(); i++) {
            JSONObject jb = new JSONObject();
            //查询订单编号是否重复(同意货主不可重复)
            Integer e = dao.getCountByBh(hzid, (String) lis.get(i).get("fybh"), ckid);
            if (e > 0) {
                sb.append("第" + lis.get(i).get("num") + "行，订单号：" + lis.get(i).get("fybh") + ",");
            }
        }
        if (sb != null && !"".equals(sb) && sb.length() > 0) {
            throw new ServiceException(sb + "数据库包含重复订单号,导入失败");
        }
    }


    /**
     * 获取订单（PO）类型
     *
     * @return
     */
    @BaseServiceDescribe(moduleName = "发运订单管理", btnName = "获取订单（PO）类型")
    public List<WmsOwnerOrdertype> getPoLx(String hzid, String ckid, String ddlx) throws ServiceException {
        try {
            return dao.getPoLx(hzid, ckid, ddlx);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("获取订单（PO）类型", e);
        }
    }


    /**
     * 根据id查找客户对象
     *
     * @param id 客户id
     * @return WmsCustomerFile
     */
    @BaseServiceDescribe(moduleName = "发运订单管理", btnName = "获取客户对象")
    public WmsCustomerFile getCusById(@Param("id") String id) throws ServiceException {
        try {
            return dao.getCusById(id);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("获取订单（PO）类型", e);
        }
    }


    /**
     * 获取字段对应的列名(发运主表)
     *
     * @param hzid 货主id
     * @param ckid 仓库id
     * @return
     */
    @BaseServiceDescribe(moduleName = "发运订单管理", btnName = "获取字段对应的列名")
    public List<WmsColumnName> getFyColumnName(String hzid, String ckid) throws ServiceException {
        try {
            return dao.getFyColumnName(hzid, ckid);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("获取发运主表字段对应的列名", e);
        }
    }

    /**
     * 获取字段对应的列名（发运明细）
     *
     * @param hzid 货主id
     * @param ckid 仓库id
     * @return
     */
    public List<WmsColumnName> getFymxColumnName(String hzid, String ckid) throws ServiceException {
        try {
            return dao.getFymxColumnName(hzid, ckid);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("获取发运明细字段对应的列名", e);
        }
    }


    /**
     * 根据列名查找该列对应的字典
     *
     * @param zcloumn 列名
     * @param hzid    货主
     * @param ckid    仓库
     * @return
     */
    public List<WmsCustomDictionary> getDictionary(String zcloumn, String hzid, String ckid) throws ServiceException {
        try {
            return dao.getDictionary(zcloumn, hzid, ckid);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("获取列名对应的字典", e);
        }
    }

    /**
     * 根据货品id 查询货品库存
     *
     * @param hpid 货品id
     * @param ckid 仓库id
     * @return
     */
    public Page<WmsStock> getGoodsStock(String hpid, int page, int rows, String ckid) throws ServiceException {
        try {
            PageHelper.startPage(page, rows);
            return (Page<WmsStock>) dao.getGoodsStock(hpid, ckid);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("获取货品的可用库存", e);
        }
    }

    /**
     * 查询库存余量
     *
     * @param ddid 发运订单id
     * @return
     */
    public Page<WmsShipmentOrderDetailed> getStockYl(String ddid, int page, int rows) throws ServiceException {
        try {
            PageHelper.startPage(page, rows);
            return (Page<WmsShipmentOrderDetailed>) dao.getStockYl(ddid);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("查询库存余量", e);
        }
    }


    /**
     * 复制单据
     *
     * @param ddid 发运订单id
     * @return
     */
    @Transactional
    @BaseServiceDescribe(moduleName = "发运订单管理", btnName = "复制订单")
    public boolean copyOrder(String ddid, String hzid, String ckid) throws Exception {
        //通过订单id 查询发运订单
        WmsShipmentOrder wmsShipmentOrder = dao.selectById(ddid);
        //修改原发运订单的复制次数，加一
        int a = dao.updateNum(wmsShipmentOrder.getNum() + 1, wmsShipmentOrder.getId());
        //根据发运订单id 查询发运明细集合
        List<WmsShipmentOrderDetailed> list = dao.wmsShipmentOrderDetailedList(ddid, hzid, ckid);
        //设置日期格式
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // new Date()为获取当前系统时间
        String date = df.format(new Date());

        /*1.选中单据点击"复制单据",生成除单号、状态外相同的订单；
        2.复制生成的单据,单据编号为 原单据号+复制次数；
        3.单据除审核状态外的所有状态为"初始"；
        4.单据审核状态为"已审核"。*/
        wmsShipmentOrder.setId(UUIDUtils.uuid());
        wmsShipmentOrder.setFyzt("0");
        wmsShipmentOrder.setCdzt("0");
        wmsShipmentOrder.setZxzt("0");
        wmsShipmentOrder.setJhzt("0");
        wmsShipmentOrder.setBczt("0");
       // wmsShipmentOrder.setDpczt("0");
        wmsShipmentOrder.setThzt("0");
        wmsShipmentOrder.setJhrwzt("0");
        wmsShipmentOrder.setShzt("1");
        wmsShipmentOrder.setCjsj(date);
        wmsShipmentOrder.setFybh(wmsShipmentOrder.getFybh() + wmsShipmentOrder.getNum());
        //增加新的订单头
        int b = dao.baseInsertSelective(wmsShipmentOrder);
        Integer c=0;
        for (WmsShipmentOrderDetailed wsod : list) {
            wsod.setId(UUIDUtils.uuid());
            wsod.setSsfyddid(wmsShipmentOrder.getId());
            wmsShipmentOrderDetailedService.insert(wsod);
            c++;
        }

        //增加新的订单明细
       // int c = wmsShipmentOrderDetailedMapper.baseInsert(list);

        //订单拆单
        SetAndModifyModel setAndModifyModel = new SetAndModifyModel();
        List<String> ids = new ArrayList<String>();
        ids.add(wmsShipmentOrder.getId());
        setAndModifyModel.setIds(ids);
      //  wmsSplitService.split(setAndModifyModel, wmsShipmentOrder.getCjr(), wmsShipmentOrder.getCkid());

        if (a > 0 && b > 0 && c > 0) {
            throw new SucessException("发运订单复制成功");
        } else {
            throw new ServiceException("发运订单复制失败");
        }
    }

    /**
     * 修改借货完结状态
     *
     * @param id 发运订单id
     * @return
     */
    public int updateJhwjzt(@Param("id") String id) throws SucessException, ServiceException {
        WmsShipmentOrder wmsShipmentOrder = dao.selectById(id);
        //单据类型为"借货",借货完结状态为"初始"的可以点击借货完结,将借货完结状态改为"完结"；
        if (wmsShipmentOrder.getShow_fylx().equals("借货") && wmsShipmentOrder.getJhwjzt().equals("0")) {
            int a = dao.updateJhwjzt(id);
            if (a > 0) {
                throw new SucessException("借货完结成功");
            } else {
                throw new ServiceException("借货完结失败");
            }
        } else {
            throw new ServiceException("只能完结 单据类型为\"借货\",借货完结状态为\"初始\"的记录");
        }

    }



    /**
     * 标记是否暂不发货
     * 标记暂不发货和取消暂不发货失败 通用一个按钮，0为标记暂不发货，1为取消暂不发货
     * @param id 发运明细id
     * @param zbfh 暂不发货状态（0、是 1、否）
     * @return
     */
    public void updateZbfh(@Param("id")String id, @Param("zbfh")String zbfh) throws SucessException, ServiceException {
        WmsShipmentOrderDetailed wmsShipmentOrderDetailed = wmsShipmentOrderDetailedMapper.selectById(id);
        //标记暂不发货
        if (zbfh.equals("0")) {
            if (wmsShipmentOrderDetailed.getZbfh().equals("0")) {
                throw new ServiceException("只能标记暂不发货状态为\"否\" 的记录");
            } else {
                int num = dao.updateZbfh(id, zbfh);
                if (num > 0) {
                    throw new SucessException("标记暂不发货成功");
                } else {
                    throw new SucessException("取消暂不发货成功");
                }
            }

        } else if (zbfh.equals("1")) {//取消标记暂不发货
            if (wmsShipmentOrderDetailed.getZbfh().equals("1")) {
                throw new ServiceException("只能取消标记暂不发货状态为\"是\" 的记录");
            } else {
                int num = dao.updateZbfh(id, zbfh);
                if (num > 0) {
                    throw new SucessException("取消标记暂不发货成功");
                } else {
                    throw new ServiceException("取消标记暂不发货失败");
                }
            }
        }
    }

    /**
     * 暂不发货订单导出
     * @param entity
     * @return
     */
    @BaseServiceDescribe(moduleName = "暂不发货订单导出", btnName = "暂不发货订单导出")
    public List<WmsShipmentOrder> baseSelectPageZBFH(WmsShipmentOrder entity){
        return dao.baseSelectPageZBFH(entity);
    }


    /**
     *  查找承运商类别
     * @return
     */
    public List<SysDictionary> selectCyslb(String d_name){
       return  dao.selectCyslb(d_name);
    }
    /**
     * 修改承运商类别
     * @param idList 发运订单id集合
     * @param cyslb 承运商类别
     * @return
     */
    @BaseServiceDescribe(moduleName = "修改承运商类别", btnName = "修改承运商类别")
    public  int updateCyslb(List<String> idList, String cyslb) throws SucessException, ServiceException {
       int a= dao.updateCyslb(idList,cyslb);
       if(a>0){
           throw new SucessException("承运商类别修改成功");
       }else{
           throw new ServiceException("承运商类别修改失败");
       }
    };

    @BaseServiceDescribe(moduleName = "查询批量打印快递面单的发运订单", btnName = "查询批量打印快递面单的发运订单")
    public List<WmsShipmentOrder>selectPrintOrder(Integer page,Integer rows,String print,String fybh,String bcbh) throws ServiceException {
        Integer p=((page-1)*rows);
        try {
            return dao.selectPrintOrder(p,rows,print,fybh,bcbh);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("查询批量打印快递面单的发运订单", e);
        }
    }

    /**
     * 选择需要批量打印快递面单的发运订单 的数量
     * @param print
     * @return
     */
    @BaseServiceDescribe(moduleName = "查询批量打印快递面单的发运订单的数量", btnName = "查询批量打印快递面单的数量")
    public  Integer  selectPrintOrderCount(String print,String fybh,String bcbh){
        return  dao.selectPrintOrderCount(print,fybh,bcbh);
    }
    //承运商预修改
    public WmsShipmentOrder getOneCys(String id){

        return dao.getOneCys(id);
    }
}
